% adn_export_csv.m
% 从 adn_results.mat 导出场景汇总 CSV（含负荷无功_Mvar）
clear; clc;

in_mat = fullfile(pwd, 'adn_results.mat');
assert(isfile(in_mat), '未找到 %s，请先运行优化并保存结果。', in_mat);

S = load(in_mat);
scenarioModels       = S.scenarioModels;
all_scenario_results = S.all_scenario_results;
nScenarios           = S.nScenarios;

summary_rows = {};

for sIdx = 1:nScenarios
    mpc = scenarioModels{sIdx};
    r   = all_scenario_results{sIdx};

    % 1) 负荷与光伏
    load_MW = sum(mpc.bus(2:4, 3));          % 负荷有功（MW）
    pv_buses = mpc.pv(:,1);
    pv_idx   = ismember(mpc.gen(:,1), pv_buses);
    pv_MW    = sum(mpc.gen(pv_idx, 2));      % 光伏有功（MW，按gen口径）

    % ★ 新增：负荷无功（Mvar），未补偿的原始需求
    Q_load_Mvar = sum(mpc.bus(2:4, 4));

    % 2) 电容器投切量（Mvar）
    Qstep_Mvar_vec = mpc.cb(:,2) * mpc.baseMVA;  % 每步 Mvar
    if isfield(r,'CB_steps') && numel(r.CB_steps)>=3
        CB_steps = r.CB_steps(:);
    else
        CB_steps = [NaN;NaN;NaN];
    end
    cb_Mvar_each = CB_steps .* Qstep_Mvar_vec;
    CB2_Mvar = cb_Mvar_each(1);
    CB3_Mvar = cb_Mvar_each(2);
    CB4_Mvar = cb_Mvar_each(3);
    CB_total_Mvar = nansum(cb_Mvar_each);

    % 3) SVG处理量（Mvar）
    Q_svg_Mvar = NaN;
    if isfield(r,'Q_svc'), Q_svg_Mvar = r.Q_svc; end

    % 4) PCC 功率因数
    if isfield(r,'pf')
        pf_pcc = r.pf;
    elseif isfield(r,'pf_slack')
        pf_pcc = r.pf_slack;
    else
        pf_pcc = NaN;
    end

    % 5) 网损/电压偏差
    loss_MW  = NaN; v_dev_pu = NaN;
    if isfield(r,'loss'),  loss_MW  = r.loss;  end
    if isfield(r,'v_dev'), v_dev_pu = r.v_dev; end

    % 6) PCC P/Q（可选但推荐保留）
    P_pcc = NaN; Q_pcc = NaN;
    if isfield(r,'P_pcc'), P_pcc = r.P_pcc; end
    if isfield(r,'Q_pcc'), Q_pcc = r.Q_pcc; end

    % 7) 组装一行
    summary_rows(end+1, :) = { ...
        sIdx, mpc.scenario_type, load_MW, pv_MW, ...
        Q_load_Mvar, ...                    % ★ 新增列：负荷无功
        CB2_Mvar, CB3_Mvar, CB4_Mvar, CB_total_Mvar, ...
        Q_svg_Mvar, pf_pcc, loss_MW, v_dev_pu, ...
        P_pcc, Q_pcc};
end

% 列名（含新增的“负荷无功_Mvar”）
summary_tbl = cell2table(summary_rows, 'VariableNames', ...
    {'场景ID','场景类型','负荷_MW','光伏_MW', ...
     '负荷无功_Mvar', ...                  % ★ 新增
     'CB2_Mvar','CB3_Mvar','CB4_Mvar','CB总量_Mvar', ...
     'SVG_Mvar','PCC_PF','网损_MW','电压偏差_pu', ...
     'P_PCC_MW','Q_PCC_Mvar'});

timestamp = datestr(now,'yyyymmdd_HHMMSS');
out_csv = fullfile(pwd, sprintf('scenario_summary_%s.csv', timestamp));
writetable(summary_tbl, out_csv, 'Encoding','UTF-8');

fprintf('已导出 CSV：%s\n', out_csv);
